package servlet;


import bean.Result;
import biz.AdminBiz;
import biz.BizException;
import biz.UserBiz;
import com.google.gson.Gson;
import dao.AdminDao;
import dao.UserDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "LoginServlet", value = "/LoginServlet.s")
public class LoginServlet extends HttpServlet {
    private AdminBiz adminBiz =new AdminBiz();
    private UserBiz userBiz =new UserBiz();
    private UserDao userDao = new UserDao();
    private AdminDao adminDao = new AdminDao();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String name = request.getParameter("name");
        final String pwd = request.getParameter("pwd");
        final String status = request.getParameter("status");
        String ucode = request.getParameter("vcode");
        //获取会话中保存的验证码，即图形界面的验证码
        Object vcode = request.getSession().getAttribute("vcode");
        System.out.println(name);
        System.out.println(pwd);
        System.out.println(status);
        Result result = null;
        final HttpSession session = request.getSession();
        if (vcode.equals(ucode)==false){
            result = new Result(0,"验证码错误",null);
        }else{
            //判断是管理员还是用户登录
            if ("用户".equals(status)){
                try {
                    //查询用户状态
                    Map<String, Object> user = userBiz.UserLogin(name, pwd);

                    Map <String,Object>  userStatus = userDao.userLogin(name,pwd,"1");
                    if (user != null && userStatus == null ){
                        result = new Result(2, "该用户账号被封禁,请联系管理员!", null);
                    }else if (userStatus !=null&&user!=null ) {
                        //登录成功
                        result = new Result(1, "登录成功!", user.get("uid"));
                    }
                } catch (BizException e) {
                    e.printStackTrace();
                    //登录失败
                    result = new Result(0,e.getMessage(),null);
                }
            }else if("管理员".equals(status)){
                try {
                    Map<String, Object> admin = adminBiz.adminLogin(name, pwd);
                    Map <String,Object> adminStatus = adminDao.adminLogin(name,pwd,"1");
                    if (admin !=null &&adminStatus ==null){
                        result = new Result(2, "该用户账号被封禁,请联系管理员!", null);
                    }else if (admin !=null){
                        result = new Result(1,"登录成功",admin.get("aid"));
                    }
                } catch (BizException e) {
                    e.printStackTrace();
                    result = new Result(0,e.getMessage(),null);
                }
            }
        }
        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }
}
